package com.disapand.mybaby.advice;

import com.disapand.mybaby.exception.ApiException;
import com.disapand.mybaby.handle.ResultCode;
import com.disapand.mybaby.handle.ResultVO;

import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import org.springframework.web.bind.MissingServletRequestParameterException;

/**
 * @author disapand
 */
@RestControllerAdvice
public class ExceptionControllerAdvice  {
    
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultVO<String> MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        /**
         * 从异常对象中拿到 ObjectError 对象
         */
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);

        /**
         * 然后提取错误提示信息进行返回
         */
        return new ResultVO<>(ResultCode.VALIDATE_FAILED, objectError.getDefaultMessage());
    }

    @ExceptionHandler(ApiException.class)
    public ResultVO<String> APIExceptionHandler(ApiException e) {
        return new ResultVO<>(ResultCode.FAILED , e.getMessage());
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ResultVO<String> MissingServletRequestParameterException(MissingServletRequestParameterException e) {
        String msg = e.getMessage();
        String param = msg != null ? msg.substring(msg.indexOf('\'') + 1, msg.lastIndexOf('\'')) : null;
        return new ResultVO<>(ResultCode.FAILED, "必要参数 " + param+ " 缺失");
    }


    @ExceptionHandler(MissingPathVariableException.class)
    public ResultVO<String> MissingPathVariableException(MissingPathVariableException e) {
        String msg = e.getMessage();
        String param = msg != null ? msg.substring(msg.indexOf('\'') + 1, msg.lastIndexOf('\'')) : null;
        return new ResultVO<>(ResultCode.FAILED, "必要参数 " + param+ " 缺失");
    }


    // MissingPathVariableException
}
